package subtyped

/**
 * Slightly adapted from parser for untyped lambda calculus by Miles Sabin 
 */
    
import scala.util.parsing.input.Reader
import scala.util.parsing.combinator.lexical.StdLexical
import scala.util.parsing.combinator.syntactical.StdTokenParsers
import scala.util.parsing.combinator.ImplicitConversions



trait TypedLambdaParser extends StdTokenParsers  with ImplicitConversions
{
  type Tokens = StdLexical
  val lexical = new StdLexical
  lexical.reserved ++= List("unit", "let", "in", "if", "then", "else","bool","int","true", "false","from","fld")
  lexical.delimiters ++= List("=>", ",",":", ".", ";", "_", "==", "(", ")", "{","}","=", "\\", "+", "-", "*", "/")

  /*

  // meaning of the argumens to the closure during subsequent iterations
  // (...(expr2 op1 expr1) ... op1 expr1)
  //      ^a^^^ ^o^ ^b^^^
  //      ^^^^^^^a^^^^^^^      ^o^ ^^b^^
  def expr1 : Parser[LTerm] =
    chainl1(expr2, expr1, op1 ^^ {o => (a: LTerm, b: LTerm) => App(App(o, a), b)})

  def expr2 : Parser[LTerm] =
   chainl1(expr3, expr2, op2 ^^ {o => (a: LTerm, b: LTerm) => App(App(o, a), b)})
  
  def expr3 : Parser[LTerm] =
   chainl1(expr4, expr3, op3 ^^ {o => (a: LTerm, b: LTerm) => App(App(o, a), b)})
  
  */
    
  def expr4 : Parser[LTerm] =
  ( "\\" ~ lambdas  
  | "let" ~ name ~ "=" ~ expr4 ~ "in" ~ expr4 ^^ flatten3(Let)
  | "if" ~ expr4 ~ "then" ~ expr4 ~ "else" ~ expr4 ^^ flatten3(If)
  | "{" ~ repsep(recordel,",") ~ "}" ^^ Record
  | "true" ^^ Tru
  | "false" ^^ Fls
  | "unit" ^^ Unit
  | "from" ~expr4~ "fld" ~ident ^^ flatten2(RecProj)
  | chainl1(aexpr, success(App(_: LTerm, _: LTerm)))
  )

  def recordel = ident ~ "="~expr4 ^^ flatten2(Tuple2[String,LTerm])
  def tyrecordel = ident ~ ":"~ltype ^^ flatten2(Tuple2[String, LType])
  
  def name : Parser[Name] = "_" ^^ Name("_") | ident ^^ Name  

  def lambdas : Parser[LTerm] = 
    name ~ ":" ~ ltype ~ ("." ~ expr4 | lambdas) ^^ flatten3(Lam)
      
  def ltype : Parser[LType]  =
    (
    "bool" ^^ TyBool
    | "int" ^^ TyInt
    | "unit" ^^ TyUnit
    | "{" ~ repsep(tyrecordel,",") ~ "}" ^^ TyRecord
  //| "(" ~ "=>" ~ "(" ~ ltype ~ "," ~ ltype ~ ")" ~")" ^^ flatten2(TyArr)
    | "(" ~ ltype ~ "=>" ~ ltype ~ ")" ^^ flatten2(TyArr)
    
    )
  
  def aexpr : Parser[LTerm] =
  ( numericLit ^^ (_.toInt) ^^ Lit
  | name ^^ Ref
//| "unit" ^^ Unit
  | "(" ~ expr4 ~ ")"
  )
  
  /*
  def op1 : Parser[LTerm] =
    "=="  ^^ Ref(Name("=="))
  
  def op2 : Parser[LTerm] =
  ( "+" ^^ Ref(Name("+"))
  | "-" ^^ Ref(Name("-"))
  )
  
  def op3 : Parser[LTerm] =
  ( "*" ^^ Ref(Name("*"))
  | "/" ^^ Ref(Name("/"))
  )
  
  */
  def parse(r: Reader[char]) : ParseResult[LTerm] =
    phrase(expr4)(new lexical.Scanner(r))
}